import { randomUUID } from "node:crypto";

import { User } from "./database/entities/user.entity.js";
import { Horny } from "./database/entities/horny.entity.js";

export class InlineQuery {
  /** @type {import("../types").IConfig} */
  #config;

  /** @param {import("../types").IConfig} config */
  constructor(config) {
    this.#config = config;
  }

  /** @param {import("grammy/out/bot").Bot} bot */
  handle(bot) {
    bot.on("inline_query", async (ctx) => await this.#answerInlineQuery(ctx));
  }

  /** @param {import("grammy/out/context").Context} ctx  */
  async #answerInlineQuery(ctx) {
    const user = await this.#getUser(ctx);
    const { hornySize, emoji } = await this.#getHorny(user);

    await ctx.answerInlineQuery(
      [
        {
          type: "article",
          id: randomUUID(),
          title: "Помощь",
          input_message_content: {
            message_text:
              "horny измеряется в размере твоего члена относительно того когда ты в холодной ванне... в мм солиднее(с) @aquanoxie\n\nsources: https://notabug.org/pawka/telegram-bot",
            parse_mode: "Markdown",
          },
        },
        {
          type: "article",
          id: randomUUID(),
          title: "Поделиться размером своего horny",
          input_message_content: {
            message_text: `Размер моего horny *${hornySize}* мм ${emoji}`,
            parse_mode: "Markdown",
          },
        },
      ],
      { cache_time: 0 },
    );
  }

  /** @param {import("grammy/out/context").Context} ctx  */
  async #getUser(ctx) {
    const { from } = ctx;
    return await User.findOneAndUpdate(
      { userId: from.id },
      {
        userId: from.id,
        firstName: from.first_name,
        lastName: from.last_name,
        username: from.username,
        languageCode: from.language_code,
        isBot: from.is_bot,
        isPremium: from.is_premium,
      },
      {
        new: true,
        upsert: true,
      },
    );
  }

  /** @param {User} user  */
  async #getHorny(user) {
    const { emoji, hornySize } = this.#calculateHorny();
    const day = this.#days();

    let horny = await Horny.findOne({ day, userId: user._id });
    if (!horny) {
      horny = await Horny.create({
        userId: user._id,
        day,
        emoji,
        hornySize,
      });
    }

    return horny;
  }

  #calculateHorny() {
    const {
      size: { range, mapEmoji },
    } = this.#config;

    const hornySize = Math.floor(Math.random() * (range.max - range.min) + range.min);
    const emoji = Object.entries(mapEmoji)
      .reverse()
      .find(([size]) => hornySize >= Number(size))
      .at(-1);

    return { emoji, hornySize };
  }

  #days() {
    return Math.floor(Date.now() / (1000 * 60 * 60 * 24));
  }
}
